<?php
namespace backend\controllers;

use Yii;
use yii\web\Controller;
use yii\data\Pagination;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use yii\helpers\Json;
use yii\web\UploadedFile;
use yii\web\ForbiddenHttpException;
use backend\models\StatisticForm;
use common\models\Product;
use yii\helpers\ArrayHelper;
use common\models\Department;
use common\models\Employees;

/**
 * 查询统计控制器
 */
class StatisticController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['query', 'statistic', 'getemployee'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }

    /**
     * [actionQuery 柱状图页面展示]
     * @return [type] [description]
     */
    public function actionQuery()
    {
        if(!Yii::$app->user->can('checkStatistic')){
            throw new ForbiddenHttpException('对不起，您现在还没获得此操作的权限');
        }
        
        $product = Product::find()->asArray()->all();
        $product = ArrayHelper::map($product, 'id', 'name');
        $department = Department::find()->asArray()->all();
        $department = ArrayHelper::map($department, 'id', 'name');

        return $this->render('query', ['product' => $product, 'department' => $department]);
    }


    /**
     * [actionQuery 查询统计]
     * @return [type] [description]
     */
    public function actionStatistic()
    {
        $data_form = new StatisticForm;

        if ($data_form->load(Yii::$app->request->get()) && $data_form->validate()) {
            $data = $data_form->query();

            return JSON::encode([
                    'flag' => true,
                    'data' => $data
                ]);
        }

        return JSON::encode([
                'flag' => false,
                'data' => $data
            ]);
    }

    /**
     * [actionGetemployee 异步获取员工信息]
     * @return [type] [description]
     */
    public function actionGetemployee()
    {
        $dids = Yii::$app->request->get()['dep'];
        $employees = Employees::find()->joinWith('empdepart')->where(['in', 'emp_depart.did', $dids])->asArray()->all();
        $employees = ArrayHelper::map($employees, 'id', 'realname');
        if ($employees) {

            return JSON::encode([
                    'flag' => true,
                    'data' => $employees
                ]);
        } else {

            return JSON::encode([
                    'flag' => false
                ]);
        }
    }

}